import React, { PureComponent } from "react";
import { push, goBack } from "react-router-redux";
import { connect } from "react-redux";
import { Form, Input, Button, Select } from "antd";
import style from "../LoginCard/style.less";
import mystyle from "./style.less";
import ThirdLogin from "../ThirdLogin";
import ErrTip from "../ErrTip";
import { GetMobileCode, loginByCode } from "../../services/api/user";
import { errCode } from "../../helper/errCode";
import SelectPhone from "../SelectPhone";
const FormItem = Form.Item;
const Option = Select.Option;

class LoginCode extends PureComponent {
  state = {
    tipFont: "获取验证码",
    disableCode: true,
    index: 6,
    timeStamp: "",
    msgCode: true,
    errimgCode: "",
    showRegister: true
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields(["mobile", "code"], (err, values) => {
      if (err) return;

      loginByCode({
        request_from: 2,
        return_type: "sync_json",
        is_store_login: 1,
        sms_type: 7,
        ...values
      }).then(data => {
        const response = data.data && data.data.data;
        const flag = String(response.flag);
        if (flag !== "0") {
          console.log(flag, errCode[flag]);
          this.props.form.setFields({
            code: {
              value: "",
              errors: [new Error(errCode[flag])]
            }
          });
        } else {
          window.location.href = "http://my.veryeast.cn";
        }
      });
    });
  };

  getCode = () => {
    this.props.form.validateFields(["mobile", "captcha"], (err, value) => {
      if (err) {
        this.setState({ errimgCode: "", showRegister: true });
        return;
      }
      if (this.state.disableCode) {
        GetMobileCode({
          ...value,
          sms_type: 7,
          country: "+86",
          return_type: "json"
        }).then(data => {
          const response = data.data;
          const flag = String(response.flag);
          if (flag !== "0") {
            console.log(flag, errCode[flag]);
            this.props.form.resetFields(["captcha"]);

            if (flag === "5101") {
              this.changeImgCode();
              this.props.form.setFields({
                captcha: {
                  value: "",
                  errors: [new Error(errCode[flag])]
                }
              });
            } else if (flag === "5120") {
              this.setState({ showRegister: false });
            } else {
              this.props.form.setFields({
                captcha: {
                  value: "",
                  errors: [new Error(errCode[flag])]
                }
              });
            }
          } else {
            this.timer = setInterval(() => {
              if (this.state.index <= 0) {
                return this.Clear();
              }
              this.setState({
                disableCode: false,
                index: this.state.index - 1,
                tipFont: `已发送(${this.state.index - 1}s)`
              });
            }, 999);
          }
        });
      }
    });
  };

  Clear = () => {
    this.setState({
      disableCode: true,
      index: 6,
      tipFont: "获取验证码"
    });
    clearInterval(this.timer);
  };

  clearErr = () => {
    this.setState({
      errimgCode: "",
      showRegister: true
    });
  };

  changeImgCode = () => {
    let date = new Date();
    let timeStamp = date.getTime();
    this.setState({ timeStamp });
  };

  componentDidMount() {}

  componentWillUnmount() {
    this.timer && this.Clear();
  }

  render() {
    const {
      tipFont,
      disableCode,
      msgCode,
      timeStamp,
      showRegister
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    const prefixSelector = getFieldDecorator("prefix", {
      initialValue: "86"
    })(<SelectPhone />);
    return (
      <div className={style.loginCard}>
        <Form onSubmit={this.handleSubmit} className={style.login}>
          <FormItem>
            <div className={style.formItem}>
              {getFieldDecorator("mobile", {
                rules: [
                  {
                    pattern: /^1[3456789]\d{9}$/,
                    message: <ErrTip>请输入正确的手机号</ErrTip>
                  },
                  { required: true, message: <ErrTip>请输入常用手机号</ErrTip> }
                ],
                initialValue: ""
              })(
                <Input
                  addonBefore={""}
                  style={{ width: "100%" }}
                  placeholder="请输入常用手机号"
                  onFocus={this.clearErr}
                />
              )}
            </div>
          </FormItem>
          <div
            className={`${mystyle.errNoregister} ${
              showRegister ? mystyle.hide : null
            }`}
          >
            该手机号未注册<a onClick={() => this.props.navigateTo("/register")}>
              立即注册
            </a>
          </div>
          <FormItem>
            <div className={style.formItem}>
              <div className={style.codeWrap}>
                {getFieldDecorator("captcha", {
                  rules: [
                    {
                      required: true,
                      message: <ErrTip>请输入图形验证码</ErrTip>
                    }
                  ]
                })(
                  <Input
                    className={`${style.formInput} ${style.code}`}
                    placeholder="请输入图形验证码"
                    onFocus={this.clearErr}
                  />
                )}
                <div className={style.imgCode} onClick={this.changeImgCode}>
                  <img src={`/u/captcha?t=${timeStamp}`} alt="" />
                </div>
              </div>
            </div>
          </FormItem>
          <FormItem>
            <div className={style.formItem}>
              <div className={mystyle.msgWrap}>
                {getFieldDecorator("code", {
                  rules: [
                    {
                      required: msgCode,
                      message: <ErrTip>请输入短信验证码</ErrTip>
                    }
                  ]
                })(
                  <Input
                    className={`${style.formInput} ${mystyle.msg}`}
                    placeholder="请输入短信验证码"
                    onFocus={this.clearErr}
                  />
                )}
                <div
                  className={`${mystyle.getMsg} ${
                    disableCode ? null : mystyle.disabledCode
                  }`}
                  onClick={this.getCode}
                >
                  {tipFont}
                </div>
              </div>
            </div>
          </FormItem>
          <div>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              登 录
            </Button>
          </div>
          <div className={`${style.register} ${mystyle.reg}`}>
            没有帐号？{" "}
            <a onClick={() => this.props.navigateTo("/register")}>立即注册？</a>
          </div>
        </Form>
        <ThirdLogin />
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {};
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    navigateTo: location => {
      dispatch(push(location));
    },
    goBack: () => {
      dispatch(goBack());
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create({})(LoginCode));
